//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using GpsSample;
using Microsoft.WindowsMobile.Samples.Location;
using System.Reflection;
using System.IO;
using System.Runtime.InteropServices;

namespace GpsTest
{
    /// <summary>
    /// Summary description for frmMain.
    /// </summary>
    public class frmMain : System.Windows.Forms.Form
    {
        private System.Windows.Forms.MenuItem exitMenuItem;
        private System.Windows.Forms.MainMenu mainMenu;
        private MenuItem menuItemGps;
        private MenuItem startGpsMenuItem;
        private MenuItem stopGpsMenuItem;

        private EventHandler updateDataHandler;
        GpsDeviceState device = null;
        GpsPosition position = null;
        private MenuItem menuItemMenu;
        private MenuItem menuItemAbout;
        private Label labelCurrentDevice;
        private Label labelCurrentDeviceTime;
        private Label labelCurrentDeviceDate;
        private Label labelCurrentGps;
        private Label labelCurrentGpsDate;
        private Label labelCurrentGpsTime;
        private MenuItem menuItemUpdate;
        private PictureBox pictureBox;
        private Timer timer;

        Gps gps = new Gps();

        string path;
        private Bitmap gpsIcon;
        private Timer timerDevice;
        private Bitmap clockIcon;
        private DateTime gpsTime = DateTime.MinValue;

        public frmMain()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            gpsIcon = new Bitmap(Path.Combine(path, "gps.png"));
            clockIcon = new Bitmap(Path.Combine(path, "clock.png"));

            pictureBox.Image = gpsIcon;
        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            base.Dispose( disposing );
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
            this.mainMenu = new System.Windows.Forms.MainMenu();
            this.menuItemUpdate = new System.Windows.Forms.MenuItem();
            this.menuItemMenu = new System.Windows.Forms.MenuItem();
            this.menuItemGps = new System.Windows.Forms.MenuItem();
            this.startGpsMenuItem = new System.Windows.Forms.MenuItem();
            this.stopGpsMenuItem = new System.Windows.Forms.MenuItem();
            this.menuItemAbout = new System.Windows.Forms.MenuItem();
            this.exitMenuItem = new System.Windows.Forms.MenuItem();
            this.labelCurrentDevice = new System.Windows.Forms.Label();
            this.labelCurrentDeviceTime = new System.Windows.Forms.Label();
            this.labelCurrentDeviceDate = new System.Windows.Forms.Label();
            this.labelCurrentGps = new System.Windows.Forms.Label();
            this.labelCurrentGpsDate = new System.Windows.Forms.Label();
            this.labelCurrentGpsTime = new System.Windows.Forms.Label();
            this.pictureBox = new System.Windows.Forms.PictureBox();
            this.timer = new System.Windows.Forms.Timer();
            this.timerDevice = new System.Windows.Forms.Timer();
            this.SuspendLayout();
            // 
            // mainMenu
            // 
            this.mainMenu.MenuItems.Add(this.menuItemUpdate);
            this.mainMenu.MenuItems.Add(this.menuItemMenu);
            // 
            // menuItemUpdate
            // 
            this.menuItemUpdate.Text = "&Update";
            this.menuItemUpdate.Click += new System.EventHandler(this.menuItemUpdate_Click);
            // 
            // menuItemMenu
            // 
            this.menuItemMenu.MenuItems.Add(this.menuItemGps);
            this.menuItemMenu.MenuItems.Add(this.menuItemAbout);
            this.menuItemMenu.MenuItems.Add(this.exitMenuItem);
            this.menuItemMenu.Text = "&Menu";
            // 
            // menuItemGps
            // 
            this.menuItemGps.MenuItems.Add(this.startGpsMenuItem);
            this.menuItemGps.MenuItems.Add(this.stopGpsMenuItem);
            this.menuItemGps.Text = "GPS";
            // 
            // startGpsMenuItem
            // 
            this.startGpsMenuItem.Enabled = false;
            this.startGpsMenuItem.Text = "Start GPS";
            this.startGpsMenuItem.Click += new System.EventHandler(this.startGpsMenuItem_Click);
            // 
            // stopGpsMenuItem
            // 
            this.stopGpsMenuItem.Text = "Stop GPS";
            this.stopGpsMenuItem.Click += new System.EventHandler(this.stopGpsMenuItem_Click);
            // 
            // menuItemAbout
            // 
            this.menuItemAbout.Text = "&About";
            this.menuItemAbout.Click += new System.EventHandler(this.menuItemAbout_Click);
            // 
            // exitMenuItem
            // 
            this.exitMenuItem.Text = "E&xit";
            this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click);
            // 
            // labelCurrentDevice
            // 
            this.labelCurrentDevice.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold);
            this.labelCurrentDevice.Location = new System.Drawing.Point(3, 4);
            this.labelCurrentDevice.Name = "labelCurrentDevice";
            this.labelCurrentDevice.Size = new System.Drawing.Size(234, 20);
            this.labelCurrentDevice.Text = "Current Device Date and Time";
            // 
            // labelCurrentDeviceTime
            // 
            this.labelCurrentDeviceTime.Location = new System.Drawing.Point(3, 44);
            this.labelCurrentDeviceTime.Name = "labelCurrentDeviceTime";
            this.labelCurrentDeviceTime.Size = new System.Drawing.Size(234, 20);
            this.labelCurrentDeviceTime.Text = "1:44 PM";
            // 
            // labelCurrentDeviceDate
            // 
            this.labelCurrentDeviceDate.Location = new System.Drawing.Point(3, 24);
            this.labelCurrentDeviceDate.Name = "labelCurrentDeviceDate";
            this.labelCurrentDeviceDate.Size = new System.Drawing.Size(234, 20);
            this.labelCurrentDeviceDate.Text = "Sunday, June 22, 2008";
            // 
            // labelCurrentGps
            // 
            this.labelCurrentGps.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold);
            this.labelCurrentGps.Location = new System.Drawing.Point(3, 64);
            this.labelCurrentGps.Name = "labelCurrentGps";
            this.labelCurrentGps.Size = new System.Drawing.Size(234, 20);
            this.labelCurrentGps.Text = "Current GPS Date and Time";
            // 
            // labelCurrentGpsDate
            // 
            this.labelCurrentGpsDate.Location = new System.Drawing.Point(3, 84);
            this.labelCurrentGpsDate.Name = "labelCurrentGpsDate";
            this.labelCurrentGpsDate.Size = new System.Drawing.Size(234, 20);
            this.labelCurrentGpsDate.Text = "Sunday, June 22, 2008";
            // 
            // labelCurrentGpsTime
            // 
            this.labelCurrentGpsTime.Location = new System.Drawing.Point(3, 104);
            this.labelCurrentGpsTime.Name = "labelCurrentGpsTime";
            this.labelCurrentGpsTime.Size = new System.Drawing.Size(234, 20);
            this.labelCurrentGpsTime.Text = "1:44 PM";
            // 
            // pictureBox
            // 
            this.pictureBox.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox.Image")));
            this.pictureBox.Location = new System.Drawing.Point(56, 137);
            this.pictureBox.Name = "pictureBox";
            this.pictureBox.Size = new System.Drawing.Size(128, 128);
            // 
            // timer
            // 
            this.timer.Enabled = true;
            this.timer.Interval = 5000;
            this.timer.Tick += new System.EventHandler(this.timer_Tick);
            // 
            // timerDevice
            // 
            this.timerDevice.Enabled = true;
            this.timerDevice.Tick += new System.EventHandler(this.timerDevice_Tick);
            // 
            // frmMain
            // 
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
            this.ClientSize = new System.Drawing.Size(240, 268);
            this.Controls.Add(this.pictureBox);
            this.Controls.Add(this.labelCurrentGpsTime);
            this.Controls.Add(this.labelCurrentGpsDate);
            this.Controls.Add(this.labelCurrentGps);
            this.Controls.Add(this.labelCurrentDeviceDate);
            this.Controls.Add(this.labelCurrentDeviceTime);
            this.Controls.Add(this.labelCurrentDevice);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Menu = this.mainMenu;
            this.MinimizeBox = false;
            this.Name = "frmMain";
            this.Text = "GPS Clock";
            this.Load += new System.EventHandler(this.frmMain_Load);
            this.Closed += new System.EventHandler(this.frmMain_Closed);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>

        static void Main() 
        {
            Application.Run(new frmMain());
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            if (gps.Opened)
            {
                gps.Close();
            }

            Close();
        }

        private void frmMain_Load(object sender, System.EventArgs e)
        {
            updateDataHandler = new EventHandler(UpdateData);
         
            gps.DeviceStateChanged += new DeviceStateChangedEventHandler(gps_DeviceStateChanged);
            gps.LocationChanged += new LocationChangedEventHandler(gps_LocationChanged);

            StartGps();
        }

        protected void gps_LocationChanged(object sender, LocationChangedEventArgs args)
        {
            position = args.Position;

            // call the UpdateData method via the updateDataHandler so that we
            // update the UI on the UI thread
            Invoke(updateDataHandler);

        }

        void gps_DeviceStateChanged(object sender, DeviceStateChangedEventArgs args)
        {
            device = args.DeviceState;

            // call the UpdateData method via the updateDataHandler so that we
            // update the UI on the UI thread
            Invoke(updateDataHandler);
        }

        void UpdateData(object sender, System.EventArgs args)
        {
            if (gps.Opened)
            {
                if (position != null)
                {
                    if (position.TimeValid)
                    {
                        gpsTime = position.Time;

                        labelCurrentGpsDate.Text = gpsTime.ToLongDateString();
                        labelCurrentGpsTime.Text = gpsTime.ToLongTimeString();
                    }
                }
            }
        }

        private void frmMain_Closed(object sender, System.EventArgs e)
        {
            if (gps.Opened)
            {
                gps.Close();
            }
        }

        private void stopGpsMenuItem_Click(object sender, EventArgs e)
        {
            if (gps.Opened)
            {
                gps.Close();
            }

            startGpsMenuItem.Enabled = true;
            stopGpsMenuItem.Enabled = false;
        }

        private void startGpsMenuItem_Click(object sender, EventArgs e)
        {
            StartGps();
        }

        private void StartGps()
        {
            if (!gps.Opened)
            {
                gps.Open();
            }

            startGpsMenuItem.Enabled = false;
            stopGpsMenuItem.Enabled = true;
        }

        private void menuItemAbout_Click(object sender, EventArgs e)
        {
            frmAbout aboutForm = new frmAbout();
            aboutForm.ShowDialog();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            if (pictureBox.Image == gpsIcon)
                pictureBox.Image = clockIcon;
            else
                pictureBox.Image = gpsIcon;
        }

        private void menuItemUpdate_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("Are you sure you wish to update your device time with your gps time?", "Alert!", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
            
            if (dialogResult != DialogResult.Yes)
                return;

            UpdateTime();
        }

        private void timerDevice_Tick(object sender, EventArgs e)
        {
            labelCurrentDeviceDate.Text = DateTime.Now.ToLongDateString();
            labelCurrentDeviceTime.Text = DateTime.Now.ToLongTimeString();
        }

        private struct SYSTEMTIME
        {
            public short Year;
            public short Month;
            public short DayOfWeek;
            public short Day;
            public short Hour;
            public short Minute;
            public short Second;
            public short Milliseconds;
        }

        [DllImport("coredll.dll")]
        private static extern bool SetSystemTime(ref SYSTEMTIME time);

        private void UpdateTime()
        {
            DateTime idag = gpsTime.ToUniversalTime();

            SYSTEMTIME s = new SYSTEMTIME();
            s.Year = (short) idag.Year;
            s.Month = (short) idag.Month;
            s.DayOfWeek = (short) idag.DayOfWeek;
            s.Day = (short) idag.Day;
            s.Hour = (short) idag.Hour;
            s.Minute = (short) idag.Minute;
            s.Second = (short) idag.Second;
            s.Milliseconds = (short) idag.Millisecond;

            SetSystemTime(ref s);
        }
    }
}
